import regEmailSendCodeApi from '@/api/user/regEmailSendCodeApi'
import { getAppNav } from '@/App'
import LocalStorageKey from '@/constant/LocalStorageKey'
import { SHA256 } from 'crypto-js'
import JsEncrypt from 'jsencrypt'
import { Dispatch, MutableRefObject, SetStateAction } from 'react'
import { randomString, ToastSuccess } from './CommonUtil'

const sendCodeDisableNumber = 60

// 发送验证码
export function sendCode(
  email: string,
  setCodeText: Dispatch<SetStateAction<string>>,
  timer: MutableRefObject<NodeJS.Timer | undefined>,
  clearTimer: () => void
) {
  setCodeText(sendCodeDisableNumber + 's')

  doRegEmailSendCodeApi(
    email,
    timer,
    clearTimer,
    sendCodeDisableNumber,
    setCodeText
  )
}

// 调用【用户注册-通过邮箱-发送验证码】接口
function doRegEmailSendCodeApi(
  email: string,
  timer: MutableRefObject<NodeJS.Timer | undefined>,
  clearTimer: () => void,
  number: number,
  setCodeText: Dispatch<SetStateAction<string>>
) {
  regEmailSendCodeApi({ email })
    .then((res) => {
      ToastSuccess(res.data.msg)
      timer.current = setInterval(() => {
        number -= 1
        if (number <= 0) {
          clearTimer()
          setCodeText('获取验证码')
          return
        }
        setCodeText(number + 's')
      }, 1000)
    })
    .catch((e) => {
      setCodeText('获取验证码')
    })
}

// 统一的 password加密
export function passwordRSAEncrypt(
  password: string,
  rsaPublicKey: string,
  date: Date = new Date()
) {
  return RSAEncryptPro(
    SHA256(SHA256(password).toString()).toString(),
    rsaPublicKey,
    date
  )
}

// 非对称加密：增强版，word 加入时间戳
export function RSAEncryptPro(
  word: string,
  rsaPublicKey: string,
  date: Date = new Date()
) {
  const timestamp = ';' + date.setMinutes(date.getMinutes() + 1) // 时间戳
  return RSAEncrypt(word + timestamp, rsaPublicKey) as string // 加入时间戳，进行非对称加密
}

// 非对称加密
export function RSAEncrypt(word: string, rsaPublicKey: string) {
  const jse = new JsEncrypt()
  jse.setPublicKey(rsaPublicKey) // 设置公钥
  return jse.encrypt(word)
}

// 登出
export function logout() {
  localStorage.removeItem(LocalStorageKey.JWT)
}

// 随机昵称
export function randomNickname() {
  return '用户昵称' + randomString(6).toUpperCase()
}
